package com.nandi.deviceinstall.net


import java.io.IOException

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory


class RetrofitClient private constructor() {
    private var apiService: APIService? = null
    private val baseUrl = "http://218.201.45.168:9999/"
//    private val baseUrl = "http://192.168.10.203:9999/"

    /**
     * 设置Header
     *
     * @return
     */
    private//添加Token
    val headerInterceptor: Interceptor
        get() = Interceptor { chain ->
            val original = chain.request()
            val requestBuilder = original.newBuilder()
                    .header("token", "")
            val request = requestBuilder.build()
            chain.proceed(request)
        }

    /**
     * 设置拦截器
     *
     * @return
     */
    private//显示日志
    val interceptor: Interceptor
        get() {

            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY

            return interceptor
        }

    //初始化一个client,不然retrofit会自己默认添加一个
    //设置Header
    //设置拦截器
    //设置网络请求的Url地址
    //设置数据解析器
    //设置网络请求适配器，使其支持RxJava与RxAndroid
    //创建—— 网络请求接口—— 实例
    val api: APIService?
        get() {
            val client = OkHttpClient().newBuilder()
                    .addInterceptor(headerInterceptor)
                    .addInterceptor(interceptor)
                    .build()

            val retrofit = Retrofit.Builder()
                    .client(client)
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build()
            apiService = retrofit.create<APIService>(APIService::class.java)
            return apiService
        }

    companion object {

        @Volatile
        private var instance: RetrofitClient? = null

        fun getInstance(): RetrofitClient? {
            if (instance == null) {
                synchronized(RetrofitClient::class.java) {
                    if (instance == null) {
                        instance = RetrofitClient()
                    }
                }
            }
            return instance
        }
    }


}
